package com.sync.data.common.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * AES加密工具类
 *
 * @author liquanchang
 */
@Component
public class AESUtils {

    // 加解密的KEY，不可修改
    public static byte[] key = {-122, -26, -93, 13, -19, -48, -123, -58, -49, -82, 14, 112, 83, 121, -111, -103};


    public static SymmetricCrypto init() {
        return new SymmetricCrypto(SymmetricAlgorithm.AES, key);
    }

    @Value(value = "${aes.key:-122, -26, -93, 13, -19, -48, -123, -58, -49, -82, 14, 112, 83, 121, -111, -103}")
    public void setAesKey(byte[] aesKey) {
        key = aesKey;
    }


    /**
     * 对字符串进行AES加密
     *
     * @param content 需要加密的内容
     */
    public static String encryptHex(String key, String content) {
        if (content == null) {
            return null;
        }
        SymmetricCrypto symmetricCrypto = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes());
        //加密为16进制表示
        return symmetricCrypto.encryptHex(content);
    }

    /**
     * 对字符串进行AES加密
     *
     * @param content 需要加密的内容
     */
    public static String encryptHex(String content) {
        if (content == null) {
            return null;
        }
        //加密为16进制表示
        return init().encryptHex(content);
    }

    /**
     * 对字符串进行AES解密
     *
     * @param content 需要解密的内容
     */
    public static String decryptStr(String content) {
        if (content == null) {
            return null;
        }

        if (StrUtil.isBlank(content)) {
            return null;
        }

        //解密为字符串
        return init().decryptStr(content, CharsetUtil.CHARSET_UTF_8);
    }

}
